<?php
  require_once("../includes/config.php");
  
    $length = 20;
    
    if( isset($_POST['page'])  && !empty($_POST['page'] ))
    {
      $page =  filter_var($_POST['page'], FILTER_SANITIZE_NUMBER_INT);
      $start = $page*20 - 20;
      unset($_POST['page']);
    }
    else
    {
      $start = 0;
      $page = 1;
    }
    
    $sql = "SELECT * FROM recipt_vouchers 
	       WHERE owner_id = ?";
    $sqlCount = "SELECT COUNT(*) FROM recipt_vouchers WHERE owner_id = ?";
    $sum= "SELECT SUM(amount) FROM recipt_vouchers WHERE owner_id = ?";
    
    $binds['owner_id'] = $_SESSION['user_id'];
  
    if(!empty($_POST['from']) && !empty($_POST['to']))
    {
      $binds['from'] = $_POST['from'];
      $binds['to'] = $_POST['to'];
      $sql .= " and miladi_date between ? AND ?";
      $sqlCount .= " and miladi_date between ? AND ?";
      $sum .= " and miladi_date between ? AND ?";
    }
	if(!empty($_POST['apart_num']) )
    {
      $binds['apart_num'] = $_POST['apart_num'];
      $sql .= " and contract_id IN ( SELECT contract_id from contract_apartments WHERE apartment_id  = ( SELECT id FROM apartments WHERE apart_name = ?)  )";
      $sqlCount .= " and contract_id IN ( SELECT contract_id from contract_apartments WHERE apartment_id  = ( SELECT id FROM apartments WHERE apart_name = ?)  )";
	  $sum .= " and contract_id IN ( SELECT contract_id from contract_apartments WHERE apartment_id  = ( SELECT id FROM apartments WHERE apart_name = ?)  )";
    }
                  
    if(!empty($_POST['contract_id']) )
    {
      $binds['contract_id'] = $_POST['contract_id'];
      $sql .= " and contract_id = ?";
      $sqlCount .= " and contract_id = ?";
	  $sum .= " and contract_id = ?";
    }
          
    if(!empty($_POST['recipet_id']))
    {
      $binds['recipet_id'] = $_POST['recipet_id'];
      $sql .= " and recipet_id = ?";
      $sqlCount .= " and recipet_id = ?";
	  $sum .= " and recipet_id = ?";
    }
    
    if(!empty($_POST['payment_method']))
    {
      $binds['payment_method'] = $_POST['payment_method'];
      $sql .= " and paymen_method = ?";
      $sqlCount .= " and paymen_method = ?";
	  $sum .= " and paymen_method = ?";
    }
          
    $sql .= " LIMIT ?,?";
    $binds['start'] = $start;
    $binds['end'] = $length;
    
    //dump($sql);
    $recipts = query($sql,$binds);
    $sqlCount = query($sqlCount,$binds);
    $sume = query($sum,$binds);
    $totalPages = $sqlCount[0]['COUNT(*)'];
    $total_sum= $sume[0]['SUM(amount)'];

    render("reciept_reports.php", array("title"=>"تقارير سندات القبض","page"=>$page,"totalPages"=>$totalPages,"recipts"=>$recipts,"start"=>$start,"length"=>$length,"binds"=>$binds,"total_sum"=>$total_sum));

?>